package com.example.myapplication.view;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.ByteArrayOutputStream;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.example.myapplication.R;


public class Test2 extends AppCompatActivity {
    Button btnGetGps ;
    Button btnTakePhoto ;
    Button btnWeb;
    private double longitude, latitude; // 存经纬度
    private byte[] photo; // 存照片
    private ActivityResultLauncher<String[]> permissionLauncher; // 权限工具
    private ActivityResultLauncher<Intent> cameraLauncher; // 相机工具

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_2); // 设界面

        // 找按钮
        btnGetGps = findViewById(R.id.btn_get_gps);
        btnTakePhoto = findViewById(R.id.btn_take_photo);
        btnWeb=findViewById(R.id.btn_web);
        btnWeb.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View v) {
                checkNetwork(); // 检查网络
            }
            // 这里可以添加打开网页的代码
            // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
            // startActivity(intent);
        });
        // 权限工具
        permissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), permissions -> {
            if (permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false)) {
                getGpsLocation(); // GPS 权限OK，定位
            } else if (permissions.getOrDefault(Manifest.permission.CAMERA, false)) {
                takePhoto(); // 相机权限OK，拍照
            } else {
                Toast.makeText(this, "需要权限", Toast.LENGTH_SHORT).show();
            }
        });

        // 相机工具
        cameraLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                Bitmap bitmap = (Bitmap) result.getData().getExtras().get("data");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
                photo = baos.toByteArray();
                Toast.makeText(this, "照片已拍", Toast.LENGTH_SHORT).show();
                 // 拍完存数据库
            }
        });

        // 按钮点击
        btnGetGps.setOnClickListener(v -> checkPermissions(true)); // GPS 按钮
        btnTakePhoto.setOnClickListener(v -> checkPermissions(false)); // 拍照按钮
    }

    // 查权限
    private void checkPermissions(boolean isGps) {
        if (isGps && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionLauncher.launch(new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
        } else if (!isGps && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            permissionLauncher.launch(new String[]{Manifest.permission.CAMERA});
        } else {
            if (isGps) {
                getGpsLocation(); // 定位
            } else {
                takePhoto();
            }
        }
    }

    // 拿 GPS
    private void getGpsLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "请开 GPS", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            return;
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }//这段强制加的
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {//间隔距离
            @Override
            public void onLocationChanged(Location location) {
                if (location != null) {
                    longitude = location.getLongitude();
                    latitude = location.getLatitude();
                    Toast.makeText(Test2.this, "经度: " + longitude + ", 纬度: " + latitude, Toast.LENGTH_SHORT).show();
                }
                locationManager.removeUpdates(this);
                insertData(); // 定位后存数据库
            }
        });
    }

    // 拍照
    private void takePhoto() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            cameraLauncher.launch(takePictureIntent);//回调
        } else {
            Toast.makeText(this, "无法开相机", Toast.LENGTH_SHORT).show();
        }
    }

    // 存数据库（占位）
    private void insertData() {//测试版
        if (longitude == 0.0 && latitude == 0.0) {
            Toast.makeText(this, "请先获取 GPS", Toast.LENGTH_SHORT).show();
            return;
        }
        // 假设 dbConnection.insert 存数据
        // boolean success = dbConnection.insert(longitude, latitude, photo);
      //  Toast.makeText(this, "数据已存", Toast.LENGTH_SHORT).show();
    }

    private void checkNetwork() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            Toast.makeText(this, "有网络", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "无网络", Toast.LENGTH_SHORT).show();
        }
    }
}